package com.fanxj.Utils;
import org.junit.Test;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.junit.Assert.assertEquals;

public class DynastyConverter {
    private static final Map<String, String> DYNASTY_MAP = new HashMap<>();
    private static final Pattern DYNASTY_PATTERN = Pattern.compile("([唐宋元明清汉])(?:代|朝|时期)?");

    static {
        // 基础朝代映射
        DYNASTY_MAP.put("唐", "唐");
        DYNASTY_MAP.put("宋", "宋");
        DYNASTY_MAP.put("元", "元");
        DYNASTY_MAP.put("明", "明");
        DYNASTY_MAP.put("清", "清");

        // 扩展模糊匹配
        DYNASTY_MAP.put("唐朝", "唐");
        DYNASTY_MAP.put("宋代", "宋");
        DYNASTY_MAP.put("元代", "元");
        DYNASTY_MAP.put("明代", "明");
        DYNASTY_MAP.put("清代", "清");
        DYNASTY_MAP.put("秦汉", "秦");
        DYNASTY_MAP.put("三国时期", "三国");
    }

    public static String convert(String rawDynasty) {
        if (rawDynasty == null || rawDynasty.isEmpty()) return null;

        // 预处理：移除多余字符
        String cleaned = rawDynasty
                .replaceAll("时期|时代|朝代|代", "")
                .trim();

        // 精确匹配优先
        if (DYNASTY_MAP.containsKey(cleaned)) {
            return DYNASTY_MAP.get(cleaned);
        }

        // 3. 正则匹配
        Matcher matcher = DYNASTY_PATTERN.matcher(cleaned);
        if (matcher.find()) {
            String dynastyKey = matcher.group(1);
            return DYNASTY_MAP.getOrDefault(dynastyKey, null);
        }

        // 4. 特殊处理（如"洪武年间"->明）
        if (cleaned.matches(".*(洪武|永乐|宣德|成化|弘治|万历|天启|嘉靖|正德).*")) return "明";
        if (cleaned.matches(".*(同治|光绪|乾隆|雍正|嘉庆).*")) return "清";


        // 默认返回原值或空字符串
//        return cleaned.length() > 2 ? "" : cleaned;
        return cleaned;
    }
//    @Test
//    public void testConvert() {
//        assertEquals("唐", DynastyConverter.convertToCode("唐太宗时期"));
//        assertEquals("宋", DynastyConverter.convertToCode("南宋"));
//        assertEquals("元", DynastyConverter.convertToCode("元代"));
//        assertEquals("古希腊", DynastyConverter.convertToCode("古希腊")); // 不支持的外来朝代
//        System.out.println(DynastyConverter.convertToCode("古希腊"));
//        System.out.println(DynastyConverter.convertToCode("弘治"));
//
//    }
}